<?php

/**
 * 操作权限类，如果要验证权限的控制器就要继承这个类
*/
class ActionController extends BaseController {

    /**
     * 调用控制器动作之前检查一下有没有访问权限
    */
    protected function beforeAction($action) {
        $action_id = $action->id;
        return $this->checkAction($action_id);
    }

    private function checkAction($action) {
        $session = Yii::app()->session;
        //系统默认用户不校验权限
        if ($session['auth']['username'] === 'admin') {
            return true;
        }
        $control = $this->getId();
        $type = Yii::app()->request->getParam('type', '');
        if (empty($type)) {
            $action_code = "{$control}/{$action}";
        } else {
            $action_code = "{$control}/{$action}/type/{$type}";
        }
        $action_list = $session['auth']['action_list'];
        $action_id = $this->getActionId($action_code);
        if (strpos($action_list, $action_id) === false) {
            $this->error('没有访问权限');
        }
        return true;
    }

    /**
     * 获取权限列表
     * @param $code string 权限代码
     * @return int 权限id
     */
    private function getActionId($code) {
        $action_list = Role::getActionList();
        if (empty($action_list)) {
            return 0;
        }
        foreach ($action_list as $action) {
            if ($action['code'] == $code) {
                return $action['id'];
            }
        }
        return 0;
    }
}